package com.lyf.boot.config;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.lyf.boot.properties.SpringDocProperties;
import com.lyf.boot.properties.XssProperties;
import com.lyf.boot.web.filter.AuthFilter;
import com.lyf.boot.web.filter.XssFilter;
import jakarta.servlet.DispatcherType;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * 过滤器
 * @author LuYufan
 * @date 2023/7/3 14:11
 */
@Configuration
@Slf4j
@AllArgsConstructor
@EnableConfigurationProperties(XssProperties.class)
public class FilterConfig {

    private final XssProperties xssProperties;

    @SuppressWarnings({"rawtypes", "unchecked"})
    @Bean
    @ConditionalOnProperty(value = "xss.enabled", havingValue = "true")
    public FilterRegistrationBean xssFilterRegistration() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setDispatcherTypes(DispatcherType.REQUEST);
        registration.setFilter(new XssFilter());
        registration.addUrlPatterns(Convert.toStrArray(xssProperties.getUrlPatterns()));
        registration.setName("xssFilter");
        registration.setOrder(FilterRegistrationBean.HIGHEST_PRECEDENCE);
        Map<String, String> initParameters = new HashMap<>(1);
        initParameters.put("excludes", CollUtil.join(xssProperties.getExcludes(), StrUtil.COMMA));
        registration.setInitParameters(initParameters);
        registration.setOrder(1);
        return registration;
    }

    @Bean
    @ConditionalOnProperty(prefix = "auth", name = "enabled", havingValue = "true")
    public FilterRegistrationBean<AuthFilter> authFilter(){
        FilterRegistrationBean<AuthFilter> registration = new FilterRegistrationBean<>();
        //注册自定义过滤器
        registration.setFilter(new AuthFilter());
        //过滤器名称
        registration.setName("authFilter");
        //过滤所有路径
        registration.addUrlPatterns("/*");
        //优先级，最顶级
        registration.setOrder(2);
        log.info("AuthFilter注入完成");
        return registration;
    }
}
